<template>
  <d2-container type="card" :filename="filename">
    <h5>{{ title }}</h5>
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>基本信息</span>
        </div>
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="一句话推荐语" prop="recommend">
          <el-input v-model="form.recommend"></el-input>
        </el-form-item>
        <el-form-item label="封面图" prop="cover_img">
          <!--<el-input v-model="form.cover_img"></el-input>-->
          <img-upload v-model="form.cover_img" :value="form.cover_img"></img-upload>
        </el-form-item>
        <el-form-item label="主图" prop="main_img">
          <!--<el-input v-model="form.main_img"></el-input>-->
          <img-upload v-model="form.main_img" :value="form.main_img"></img-upload>
        </el-form-item>
        <el-form-item label="缩略图" prop="thumb">
          <!-- <el-input v-model="form.thumb"></el-input> -->
          <img-upload v-model="form.thumb" :value="form.thumb"></img-upload>
        </el-form-item>
      </el-card>
      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>分类信息</span>
        </div>
        <el-form-item label="所属课程ID" prop="course_id" v-if="diffKeys && diffKeys.split(',').some(d => d === 'course_id')">
          <el-input v-model="form.course_id"></el-input>
        </el-form-item>
        <el-form-item label="主分类" prop="category_main_id">
          <tree-select v-model="form.category_main_id"
             :expendKeys="expendKeys"
             :treeData="categoryTree"></tree-select>
        </el-form-item>
        <el-form-item label="次分类" prop="category_sub_id">
          <tree-select v-model="form.category_sub_id"
                       :expendKeys="expendKeys"
                       :treeData="categoryTree"></tree-select>
        </el-form-item>
        <el-form-item label="三级分类" prop="category_l3_id">
          <tree-select v-model="form.category_l3_id"
                       :expendKeys="expendKeys"
                       :treeData="categoryTree"></tree-select>
        </el-form-item>
        <el-form-item label="标签1" prop="label1">
          <el-input v-model="form.label1"></el-input>
        </el-form-item>
        <el-form-item label="标签2" prop="label2">
          <el-input v-model="form.label2"></el-input>
        </el-form-item>
        <el-form-item label="标签3" prop="label3">
          <el-input v-model="form.label3"></el-input>
        </el-form-item>
      </el-card>
      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>多媒体信息</span>
        </div>
        <el-form-item label="音频持续时长" prop="resource_duration">
          <el-input type="number" v-model="form.resource_duration" placeholder="单位：秒"></el-input>
        </el-form-item>
        <el-form-item label="音频文件大小" prop="resource_size">
          <el-input type="number" v-model="form.resource_size" placeholder="单位：KB"></el-input>
        </el-form-item>
        <el-form-item label="音频文件链接" prop="resource_url">
          <el-input type="text" v-model="form.resource_url"></el-input>
        </el-form-item>
      </el-card>

      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>作者信息</span>
        </div>
        <el-form-item label="作者姓名" prop="description">
          <el-input type="text" v-model="form.author_name"></el-input>
        </el-form-item>
        <el-form-item label="作者头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :data="qiniuData"
            :show-file-list="false"
            :on-success="onUploadSuccess"
            :on-error="onUploadError"
            :before-upload="onBeforeUpload">
            <img v-if="avatarUrl" :src="avatarUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-card>

      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>销售信息</span>
        </div>
        <el-form-item label="原始价格" prop="price_origin">
          <el-input type="number" v-model="form.price_origin"></el-input>
        </el-form-item>
        <el-form-item label="当前价格" prop="price_current">
          <el-input type="number" v-model="form.price_current"></el-input>
        </el-form-item>
      </el-card>

      <el-card class="box-card mt20" shadow="hover">
        <div slot="header" class="clearfix">
          <span>文章内容</span>
        </div>
        <el-row :gutter="40">
          <el-col :span="14">
            <d2-ueditor v-model="form.content" ref="editor" />
          </el-col>
          <el-col :span="8">
            <el-card v-if="form.content" shadow="never" style="border: 1px solid #d4d4d4;">
              <template slot="header">内容预览</template>
              <div v-html="form.content" style="margin: -20px 0px;"></div>
            </el-card>
          </el-col>
        </el-row>
      </el-card>
    </el-form>

    <template slot="footer">
      <el-button type="primary" @click="onSave">
        <d2-icon name="save"/> 保存
      </el-button>
      <el-button type="danger" @click="onCancel">
        <d2-icon name="cancel"/> 取消
      </el-button>
    </template>
  </d2-container>
</template>

<script>
import request from '@/plugin/axios'
import * as qiniu from 'qiniu-js'
import settings from '@/setting'
import categoryUtils from '@/libs/util.category'
// import TreeSelect from '@/components/custom-column/tree-select'

export default {
  name: 'CourseEdit',
  props: {
    // 面包屑
    title: {
      type: String,
      require: true
    },
    // 页面加载列表数据的URL
    dataUrl: {
      type: String,
      require: true
    },
    // 编辑器对应的页面URL的name
    listPathName: {
      type: String,
      require: true
    },
    // 模块间有差异的部分项
    diffKeys: {
      type: String
    }
  },
  data () {
    return {
      categoryTree: [], // 分类对应的树形数据
      expendKeys: [],
      uploadUrl: '',
      qiniuData: {
        key: '',
        token: settings.qiniu.token
      },
      form: {
        /* 基本信息 */
        title: '', // 章节标题
        description: '', // 章节描述信息
        recommend: '', // 一句话推荐语
        content: '', // 文章内容
        cover_img: '', // 封面图URL
        main_img: '', // 章节主图
        thumb: '', // 缩略图

        /* 多媒体信息 */
        resource_duration: 0, // 相关音频文件持续时长
        resource_size: 0, // 相关音频文件的大小
        resource_url: '', // 相关音频文件的URL

        /* 作者信息 */
        author_name: '', // 作者姓名
        author_avatar: '', // 作者头像
        // author_id: 0, // 作者ID，需要suggest

        /* 分类信息 */
        // category_main_id: '', // 分类的主ID
        // category_sub_id: '', // 分类的次ID
        // category_l3_id: '', // 分类的三级ID
        keywords: '', // 章节关键词
        label1: '', // 章节标签
        label2: '', // 章节标签
        label3: '', // 章节标签

        // create_time: 0, // 文章创建时间默认值
        price_current: 0, // 章节当前价格
        price_origin: 0 // 章节原价
        // status: 0
      },
      imageUrl: '', // 上传的图片的URL
      rules: {},
      avatarUrl: '', // 用户头像URL
      id: '', // 当前章节的ID
      filename: __filename,
      text: '<p>Hello World</p>'
    }
  },
  methods: {
    onSave () {
      // http://www.dianzedushu.com:8000/api/v1/study/courses?title=测试文章&price_origin=100&price_current=100
      this.form.price_origin = +this.form.price_origin
      this.form.price_current = +this.form.price_current
      let postData = ''

      let formData = new FormData()

      for (var k in this.form) {
        if (typeof this.form[k] !== 'object') {
          if (k === 'content') {
            formData.append(k, this.$refs.editor.getContent())
            // postData += k + '=' + this.$refs.editor.getContent() + '&'
          } else {
            formData.append(k, this.form[k])
            // postData += k + '=' + this.form[k] + '&'
          }
        }
      }

      console.log('POST的数据为：', postData)
      if (this.id) {
        // 编辑数据
        // request.put(this.dataUrl + '/' + this.id, postData).then(response => {
        request.put(this.dataUrl + '/' + this.id, formData).then(response => {
          this.$router.push({ name: this.listPathName })
        }).catch(() => {})
      } else {
        // 新增数据
        request.post(this.dataUrl, postData).then(response => {
          this.$router.push({ name: this.listPathName })
        }).catch(() => {})
      }
    },
    onCancel () {
      this.$router.push({ name: this.listPathName })
    },
    onUploadSuccess (res, file) {
      this.avatarUrl = settings.qiniu.imageEcho + res.key
    },
    onUploadError (res, file) {
    },
    onBeforeUpload (file) {
      this.qiniuData.key = file.name
    },
    handleAvatarSuccess () {
    },
    beforeAvatarUpload () {
    }
  },
  created () {
    this.id = this.$route.params.id
    console.log('当前的ID为：', this.id)
    if (this.id) {
      // 获取当前的课程详情
      let url = this.dataUrl + '/' + this.id
      request.get(url).then(response => {
        console.log(response)
        delete response.findStatistics // 暂时去除掉findStatistics属性，不需要编辑
        delete response.studyStatistics // 学习模块中的统计属性，不需要编辑
        this.form = response
      }).catch(function (error) {
        console.log(error)
      })
    }

    let config = {
      useCdnDomain: true,
      disableStatisticsReport: false,
      retryCount: 6,
      region: qiniu.region.z0
    }
    qiniu.getUploadUrl(config, this.qiniuData.token).then(res => {
      console.log('上传URL为：', res)
      this.uploadUrl = res
    })

    categoryUtils.getCategoryTree().then(data => {
      this.categoryTree = data
      this.expendKeys = [data[0].id] // 默认将第一级展开
    }).catch(err => {
      console.warn(err)
    })
  }
}
</script>
<style scoped>
  .mt20 {
    margin-top: 20px;
  }
</style>
